
// @ccclass('Tw')
cc.Class({
    extends: cc.Component,

    properties: {
        layerReady:{
            default: null,
            type: cc.Node
        },
        layerGame:{
            default: null,
            type: cc.Node
        },
        layerZhanTing:{
            default: null,
            type: cc.Node
        },
        layerFail:{
            default: null,
            type: cc.Prefab
        },
        prefab_block:{
            default: null,
            type: cc.Prefab
        },
        prefab_star:{
            default: null,
            type: cc.Prefab
        },
        //一个块的分数
        prefab_blockScore:{
            default: null,
            type: cc.Prefab
        },
        block_parent:{
            default: null,
            type: cc.Node
        },
        star_parent:{
            default: null,
            type: cc.Node
        },
        node_ChuiZi:{
            default: null,
            type: cc.Node
        },
        node_Tuya:{
            default: null,
            type: cc.Node
        },
        bg_node_Tuya:{
            default: null,
            type: cc.Node
        },
        audio_sound:{
            type:[cc.AudioClip],
            default:[]
        },

    },
    /* @author: seagull  @change:利用json文件读取关卡配置
     * @date: 2024/10/13 10:13 */
    LoadJson: function() {
        this.Config_guanka = {}; 
        var self = this;
    
        cc.resources.load('JSON/GuanKa',function (err, object) {
            if (err) {
                console.log(err); 
                return;
            }
            self.Config_guanka = object.json;
        });
    },
    onLoad () { 
        //设置当前脚本为全局
        window.starGame = this;
        this.LoadJson();
        

        this.bg = this.node.getChildByName('Bg');
        this.Label_Guanka = this.layerGame.getChildByName('Label_Guanka');
        this.Label_Score = this.layerGame.getChildByName('Label_Score');

        this.tip_success = this.layerGame.getChildByName('tip_guoGuan').getChildByName('tip_success');
        //消除鼓励动画
        this.ani_good = this.layerGame.getChildByName('ani_good'); 
        for(let i=0;i< this.ani_good.children.length;i++){
            this.ani_good.children[i].opacity = 0;
        }
        
        this.layerGame.active = false;
        this.layerReady.active = true;
        this.layerZhanTing.active = false;

        //创建星星相关数值
        this.black_size = 64;
        this.black_interval = 4;
        this.black_num_width = 10;
        this.black_num_height = 10;

        this.time_indicate = 0;//用于自动提示功能
        /* @author: seagull  @change:当前分数与存储分数
         * @date: 2024/10/11 16:19 */
         
        this.curScore = 0;
        this.lb_curScore = this.layerGame.getChildByName('lb_curScore').getComponent(cc.Label);
        this.lb_lianXiao = this.layerGame.getChildByName('lb_lianXiao')

        //开局隐藏
        this.node_ChuiZi.active = false;
        this.node_Tuya.active = false;
        this.bg_node_Tuya.active = false;

        //声明角标二维数组
        this.arr_blocks = [];
        for(let i = 0; i < this.black_num_width; i++){
            this.arr_blocks[i] = [];
        }
        this.clean();

        //星星的容器大小
        this.Setparent();
        //锤子
        //调用函数
        // this.createAllBlock();
        this.setTouch();
        /* @author: seagull  @change:添加开始动画AniStart()，先设置一个游戏状态
         * @date: 2024/09/19 14:07 */
         this.gameStatus = 0;//0 游戏开始前，1 游戏进行时,2 游戏结束
         //关卡
         this.levelNum = 0;
         this.TargetScore = 1000;

        
         //微信平台
        if(this.isWxplatform()){
            this.userData = wx.getStorage('userData_xmxx');
        }else{
            this.userData = JSON.parse(cc.sys.localStorage.getItem('userData_xmxx'))
        }
         this.setUserData();
        //  cc.sys.localStorage.removeItem('userData_xmxx')

         this.is_sound = true;

        /* @author: seagull  @change:屏幕适配
         * @date: 2024/10/14 11:04 */
        var fbl_sheBei = cc.director.getWinSizeInPixels()
        console.log('宽：'+fbl_sheBei.width + ' 高：'+fbl_sheBei.height);
        var f_scale = fbl_sheBei.width / 720.0
        this.block_parent.scale = f_scale * 720.0 / this.block_parent.width
        this.star_parent.scale = f_scale * 720.0 / this.block_parent.width
        let btnToolLayout = this.layerGame.getChildByName("Btn_Tool_Layout");
        btnToolLayout.scale = f_scale
    },
    //存储数据
    setUserData:function(){
        if (!this.userData) {
            this.userData = {
                arrBblocks_save: [],
                numLevel_save: 1,
                curScore_save: 0,
                numScore_fh: 0,
                score_best: 0,
            };
        }
        //如果是微信平台
        if (this.isWxplatform()) {
            //微信平台
            wx.setStorage({
                key: 'userData_xmxx',
                data: JSON.stringify(this.userData),
                success: function (res) {
                    console.log('存储成功')
                }
            })
        }else{
            cc.sys.localStorage.setItem('userData_xmxx', JSON.stringify(this.userData));
        }
        
    },
    isWxplatform:function(){
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            return true;
        }
        return false;
    },

    //设置父节点
    Setparent: function(){
        //星星的容器大小
        this.block_parent.width =( this.black_size + this.black_interval) * this.black_num_width + this.black_interval;
        this.block_parent.height = (this.black_size + this.black_interval) * this.black_num_height + this.black_interval
        this.block_parent.y = -this.block_parent.parent.height / 2 + this.block_parent.height / 2 + 80;
        this.star_parent.width = this.block_parent.width;
        this.star_parent.height = this.block_parent.height;
        this.star_parent.y = this.block_parent.y;
    },
    ContinueStart(){
        /* @author: seagull  @change:创建星星前先消除所有星星
        * @date: 2024/09/28 12:54 */
        this.clean();
        this.setToolBtnInteractable(false);
        this.lb_curScore.string = this.curScore;
        this.tip_success.active = false;
           
        this.gameStatus = 1;
        this.createAllBlockByLocal();
        this.setToolBtnInteractable(true);
        this.Label_Guanka.getComponent(cc.Label).string = "关卡："+this.levelNum;
        this.Label_Score.getComponent(cc.Label).string = "目标分数："+this.TargetScore;
        
    },
    //点击开始游戏按钮调用
    AniStart(){
        this.userData.numScore_fh = this.curScore;
        this.setUserData();
        /* @author: seagull  @change:创建星星前先消除所有星星
        * @date: 2024/09/28 12:54 */
        this.clean();
        this.setToolBtnInteractable(false);
        this.lb_curScore.string = this.curScore;
        this.tip_success.active = false;
       
         //创建星星
        this.createAllBlock();   
        this.levelNum ++;
        this.TargetScore = this.Config_guanka[this.levelNum]["targetScore"]
        
        let ani_label_guanka = this.layerGame.getChildByName("ani_label_guanka");
        let ani_label_score = this.layerGame.getChildByName("ani_label_score");
        ani_label_guanka.getComponent(cc.Label).string = "关卡："+this.levelNum;
        ani_label_score.getComponent(cc.Label).string = "目标分数："+this.TargetScore;
         this.Label_Guanka.getComponent(cc.Label).string = "关卡："+this.levelNum;
        this.Label_Score.getComponent(cc.Label).string = "目标分数："+this.TargetScore;
        let delayTime =1;
        
    //     this.block_parent.y += this.bg.height/2 + this.block_parent.height;
        
        ani_label_guanka.x = this.bg.width + 200;
        ani_label_score.x = this.bg.width + 200;

        if(this.curScore >= this.TargetScore && !this.tip_success.active) {
            this.tip_success.active = true;
            let play_success = this.tip_success.getComponent(cc.Animation);
             //播放动画
             play_success.play("Success");
        }
    {      
        cc.tween(ani_label_guanka)
          .to(0.5,{x:0},{easing: "cubicIn"})
          .delay(delayTime + 0.2)
          .to(0.5,{x:-this.bg.width/2 - 200},{easing: "cubicOut"})
          .call(()=>{
            this.gameStatus = 1;
          })
          .start();
    }
    {      
        cc.tween(ani_label_score)
          .to(0.7,{x:0},{easing: "cubicIn"})
          .delay(delayTime)
          .to(0.5,{x:-this.bg.width/2 - 200},{easing: "cubicOut"})
          .call(()=>{
          })
          .start();
    }
        let children = this.block_parent.children;
        for(let i=0;i<children.length;i++){
            children[i].y = children[i].y + 1500;
            cc.tween(children[i])
              .delay(2.2)
              .by(0.5 + i*0.01,{ position: cc.v2(0, -1500)},{easing: "cubicIn"})
              .call(()=>{
                this.setToolBtnInteractable(true);
            })
            .start();
        }

    },
    /* @author: seagull  @change:读取本地方块的二维数组数据
     * @date: 2024/10/13 16:42 */
    getStarData(){
        let data = cc.sys.localStorage.getItem("starData");
        return data;
    },

    start () {

    },
    //创建所有星星
    createAllBlock: function () {

        //设置星星初始位置
        let block_strat_x = -this.block_parent.width / 2 + this.black_size / 2 +this.black_interval;
        let block_start_y = -this.block_parent.height / 2 + this.black_size / 2 + this.black_interval ;
        for(var j = 0; j < this.black_num_height; j++){
            for(var i = 0; i < this.black_num_width; i++){
                var block = cc.instantiate(this.prefab_block);
                // block.parent = this.block_parent;
                
                block.x = block_strat_x + i * (this.black_size + this.black_interval);
                block.y = block_start_y + j * (this.black_size + this.black_interval);

                //获得block的脚本文件
                let js_block = block.getComponent("block");
                let index_ran = Math.floor(Math.random() * 5);
                js_block.init(index_ran);
                this.block_parent.addChild(block);
                
            }
        }
        this.refreshArr();
    },
    //创建所有星星通过本地存储
    createAllBlockByLocal: function () {

        //设置星星初始位置
        let block_strat_x = -this.block_parent.width / 2 + this.black_size / 2 +this.black_interval;
        let block_start_y = -this.block_parent.height / 2 + this.black_size / 2 + this.black_interval ;
        for(var j = 0; j < this.black_num_height; j++){
            for(var i = 0; i < this.black_num_width; i++){
                var num_save = this.userData.arrBblocks_save[j][i];
                if (num_save == -1) {
                    continue
                }
                var block = cc.instantiate(this.prefab_block);
                block.parent = this.block_parent;
                
                block.x = block_strat_x + i * (this.black_size + this.black_interval);
                block.y = block_start_y + j * (this.black_size + this.black_interval);

                //获得block的脚本文件
                let js_block = block.getComponent("block");
                js_block.init(num_save);
                
            }
        }
        this.refreshArr();
    },
    //通过元素块的坐标获得二维数据的角标
    getArrByPos: function(pos){
        // console.log(pos);
        let x = this.block_parent.width / 2 + pos.x;
        let y = this.block_parent.height / 2 + pos.y;

        let xx = Math.floor(x / (this.black_size + this.black_interval));
        let yy = Math.floor(y / (this.black_size + this.black_interval));

        //console.log("pos_x:",xx,"pos_y:",yy)
        return cc.v2(yy,xx);
    },
    //刷新二维数组
    refreshArr: function(){
        // this.arr_blocks = Array.from({ length: this.black_num_height }).map(
        //     () => Array.from({ length:  this.black_num_width }).fill(-1)
        //   );
          
        for(let i = 0; i < this.black_num_height; i++){
            for(let j = 0; j < this.black_num_width ; j++){
                this.arr_blocks[i][j] = -1;
            }
        }

        let child = this.block_parent.children; //获取子节点
        for(let ii = 0; ii < child.length; ii++){
            let childPos = child[ii].getPosition();
            let pos_arr = this.getArrByPos(childPos);
            let type_block = child[ii].getComponent("block").blockType;
            // this.arr_blocks[pos_arr.x] = [];
            this.arr_blocks[pos_arr.x][pos_arr.y] = type_block;
        }
        console.log(this.arr_blocks);

    },
    //判断游戏是否结束
    isGameOver: function(){
        for(let i = 0; i < this.black_num_height; i++){
            for(let j = 0; j < this.black_num_width ; j++){
                if(this.arr_blocks[i][j] != -1){
                    if(i+1 < this.black_num_height && this.arr_blocks[i+1][j] == this.arr_blocks[i][j]){
                        return false;
                    }else if(j+1 < this.black_num_width && this.arr_blocks[i][j+1] == this.arr_blocks[i][j]){//判断是否相邻
                        return false;
                    }else if(i-1 >= 0 && this.arr_blocks[i-1][j] == this.arr_blocks[i][j]){//判断是否相邻
                        return false;
                    }else if(j-1 >= 0 && this.arr_blocks[i][j-1] == this.arr_blocks[i][j]){//判断是否相邻
                        return false;
                    }
                }
            }
        }
       
        return true;
    },
    //游戏结束动画
    actGameOver: function(){
        this.gameStatus = 2;
        var children = this.block_parent.children
        for (let i = children.length-1; i >= 0; i--) {
            
            var act_1 = cc.blink(1.5,4)
            var act_2 = cc.delayTime(0.03*i)
            var act_3 = cc.callFunc(function(){
                var pos_block = children[i].getPosition()
                var blockType = children[i].getComponent('block').blockType
                for (let i = 0; i < 3; i++) {
                    this.createStar(pos_block,blockType)
                }
                children[i].active = false
            },this)

            var end = cc.sequence(act_1,act_2,act_3)
            children[i].runAction(end)
            
        }
       
        let time_bg = 2.5 + (children.length - 1)*0.03;
        this.scheduleOnce(function(){    
            //如果分数没到达目标分数，则显示失败界面
            if(this.TargetScore > this.curScore){
                this.showFail();
            }else{
                this.AniStart();
            }
        },time_bg);

    },
    showFail: function(){
        this.userData.arrBblocks_save = [];
        this.userData.numLevel_save = 0;
        this.userData.curScore_save = 0;
        this.setUserData();

        let layerFail = cc.instantiate(this.layerFail);
        let bg = layerFail.getChildByName("bg_music");
        bg.scale = 0;
        layerFail.parent = this.node;
        layerFail.setPosition(cc.v2(0,0));
        
        cc.tween(bg)
            .parallel(
                cc.tween().to(0.36,{scale:1}),
                cc.tween().repeat(360,cc.tween().by(0.001,{angle: 1}))
            )
            .start();
    },
    //消除后移动块
    moveBlock_down: function(){
        let children = this.block_parent.children;
        let f_time_big = 0.08;
        let f_time_1 = 0.08
        for(let i = 0; i < children.length; i++){
            let childPos = children[i].getPosition();
            let posBlock = this.getArrByPos(childPos);
            //空块
            let i_null = 0;

            //移动空块来设置时间

            for(let j = posBlock.x ; j >= 0; j--){
                if(this.arr_blocks[j][posBlock.y] == -1){
                    i_null ++;
                }
            }
            cc.tween(children[i])
            .by(f_time_1,{position: cc.v2(0,-(this.black_size + this.black_interval) * i_null)})
            .call(()=>{
                
                
            })
            .start();            
        }
        this.scheduleOnce(function() {
            this.refreshArr()
            this.moveBlock_Left()
        }, f_time_big+0.02);
        


    },
    moveBlock_Left: function(){
        let children = this.block_parent.children;
        let f_time_big = 0.08;
        let f_time_1 = 0.08
        for(let i = 0; i < children.length; i++){
            let childPos = children[i].getPosition();
            let posBlock = this.getArrByPos(childPos);
            //空块
            let j_null = 0;

            for(let j = posBlock.y ; j >= 0; j--){
                if(posBlock.x != 0 ){
                    continue;
                }
                if(this.arr_blocks[posBlock.x][j] == -1){
                    j_null ++;
                }
            }
            if(j_null > 0){
                for(let iij=0;iij<children.length;iij++){
                    let childPos_move = children[iij].getPosition();
                    let posBlock_move = this.getArrByPos(childPos_move);
                    if(posBlock_move.y == posBlock.y){
                        cc.tween(children[iij])
                        .by(f_time_1,{position: cc.v2(-(this.black_size + this.black_interval) * j_null,0)})
                        .call(()=>{
                         })
                        .start();
                        
                    }
                }
            }
        }
        if(this.is_sound){
            cc.audioEngine.play(this.audio_sound[1], false, 1);
        }
        this.userData.arrBblocks_save = this.arr_blocks;
        this.userData.numLevel_save = this.levelNum;
        this.userData.curScore_save = this.curScore;
        this.setUserData();
        
        this.scheduleOnce(function() {
            this.refreshArr();

            if(this.isGameOver()){
                this.actGameOver();
                console.log("game over1111 moveBlock_Left");
            }else{
                console.log("game continue111 moveBlock_Left");
            }
        }, f_time_big+0.02);
    },
    logArray: function(){
        for(let i = this.black_num_height; i >= 0; i--){
            console.log("数组",this.arr_blocks[i]);
        }
    },
    //屏幕触摸事件
    setTouch: function(){

        this.block_parent.on('touchstart',function(event){
        let pos_start_world = event.getLocation();//获得世界坐标，需要转化为相对于节点block_parent的坐标
        let pos_start_node = this.block_parent.convertToNodeSpaceAR(pos_start_world);

        // console.log(pos_start_node);

        //获得每一个块的区域
        let children = this.block_parent.children;
        //锤子动画
        //第二次触摸时如果当前块没有被选中则停止动画
        //先停止动画
        for(var j = 0; j < children.length; j++){   
            let click_anim = children[j].getComponent(cc.Animation);
            let state_anim = click_anim.getAnimationState("click_block");         
            let Rerect = children[j].getBoundingBox();
            let iscuizi = children[j].getComponent("block").get_IsChuiZZi();
            let isTuya = children[j].getComponent("block").get_IsTuya();
            let childPos = children[j].getPosition();
            let type_block = children[j].getComponent("block").blockType;
            if(Rerect.contains(pos_start_node)){
                
                if(state_anim.isPlaying){
                    this.CanDesdroy(true);
                }else{
                    this.CanDesdroy(false);
                }
                //锤子效果
                if(iscuizi){
                    console.log("可以锤了");
                    let animChuiZi = this.node_ChuiZi.getComponent(cc.Animation);
                    animChuiZi.play("ChuiZi");
                    let ones = animChuiZi.play("ChuiZi");
                    let test = j;
                    ones.once('lastframe',()=>{
                        children[test].removeFromParent();
                        this.node_ChuiZi.active = false;
                        for(let count = 0; count < 5; count++){
                            this.createStar(childPos,type_block);
                        }
                        this.refreshArr();
                        this.moveBlock_down();
                        this.setToolBtnInteractable(true);
                    },this);         

                }else if(isTuya){
                    let test = j;
                    children[test].getComponent("block").set_IsTuya(true);
                    this.setToolBtnInteractable(true);
                }
                else{
                    // this.setToolBtnInteractable(true);
                    // console.log("换一个锤子🔨");
                    this.NoNChuiZi();
                    this.NoNTuya();
                }
                
            }
        }
        for(var i = 0; i < children.length; i++){
            let rect = children[i].getBoundingBox();
            if(rect.contains(pos_start_node)){
                if(this.is_sound){
                    cc.audioEngine.play(this.audio_sound[2], false, 1);
                }
                // console.log("点击了第" + i + "个块,该块位置为",children[i].getPosition());
                if(this.node_ChuiZi.active){//有锤子特效🔨
                    this.node_ChuiZi.setPosition(children[i].getPosition())
                    this.node_ChuiZi.x = children[i].x + 20;
                    children[i].getComponent("block").set_IsChuiZZi(true);
                    return;
                }else if(this.node_Tuya.active){//有涂鸦特效
                    console.log("有涂鸦特效");
                    this.node_Tuya.setPosition(children[i].getPosition())
                    this.node_Tuya.x = children[i].x + 20;
                    this.node_Tuya.y = children[i].y + 40;
                    children[i].getComponent("block").set_IsTuya(true);
                    this.btnBg_Tuya_apprence(i);
                    return;
                }
                this.touchOne(i);
            }
        }
        },this)


    },
    //当前点击是否可以消除
    CanDesdroy: function(isDestory){

        let children = this.block_parent.children;
        let arr_destroy = [];
        for(var i = 0; i < children.length; i++){
            let click_anim = children[i].getComponent(cc.Animation);
            let state_anim = click_anim.getAnimationState("click_block"); 
            if(isDestory){
                if(state_anim.isPlaying){
                    arr_destroy.push(children[i]);
                }
            }else{
                click_anim.setCurrentTime(0,"click_block");
                click_anim.stop("click_block");
            }

        }
        

        if(arr_destroy.length > 1){
           
            let num = -1;
            let curnum =  0;
            for(var i = 0; i < arr_destroy.length; i++){
                let getPos = arr_destroy[i].getPosition()
                let blockType = arr_destroy[i].getComponent("block").blockType;
                arr_destroy[i].removeFromParent();
                //消除动画
                for(let j = 0; j < 5; j++){
                    this.createStar(getPos,blockType)
                }
                num ++;
                let prefab_blockScore = cc.instantiate(this.prefab_blockScore);
                prefab_blockScore.parent = this.star_parent
                prefab_blockScore.setPosition(getPos);

                let blockScoreScript = prefab_blockScore.getComponent("destoryBlockScript");
                let f_score = 5 + num * 10;
                let f_time = 0.03 * num + 0.2;
                //把父节点坐标转化为世界坐标
                let pos_world = this.layerGame.convertToWorldSpaceAR(this.layerGame.getChildByName('lb_curScore').getPosition());
                //吧世界坐标转化相对于节点的坐标
                let f_pos = this.star_parent.convertToNodeSpaceAR(pos_world);

                blockScoreScript.init(f_score,f_time,f_pos);

                curnum += 5 + num * 10;
               
            }
            this.lb_lianXiao.getComponent(cc.Label).string = arr_destroy.length + '连消'+curnum+'分';
            //连消动画，渐显，渐隐
            cc.tween(this.lb_lianXiao)
                .to(0.2,{opacity:255})
                .delay(0.2)
                .to(0.2,{opacity:0})
                .call(()=>{
                })
                .start();
            //good 动画
            let GoodChildren = this.ani_good.children;
            let randomI = Math.floor(Math.random()*GoodChildren.length -1);
            if(arr_destroy.length>=5){
                if(this.is_sound){
                    cc.audioEngine.play(this.audio_sound[0], false, 1);
                }
                for(let index=0;index<GoodChildren.length;index++){
                    if(index == randomI){
                        cc.tween(GoodChildren[index])
                            .to(0.2,{opacity:255})
                            .delay(0.2)
                            .to(0.2,{opacity:0})
                            .call(()=>{
                            })
                           .start();
                    }else{
                        GoodChildren[index].opacity = 0;
                    }
                }
            }                     
            
            /* @author: seagull  @change:消除之后判断游戏是否结束,后启动下一关
            * @date: 2024/09/28 12:44 */
            if(this.block_parent.children == 0){
                   this.AniStart();
            }
            this.time_indicate = 0;//自动提示时间清零
            this.refreshArr();
            this.moveBlock_down();
        }

    },
    //分数累加
    addScore: function(score){
        this.curScore += score;
        this.userData.curScore_save = this.curScore;
        this.setUserData();
        this.lb_curScore.string = this.curScore;
        if(this.curScore >= this.TargetScore && !this.tip_success.active) {
            this.tip_success.active = true;
            let play_success = this.tip_success.getComponent(cc.Animation);
             //播放动画
             play_success.play("Success");
        }
        
    },


    //点中了一块S
    touchOne: function(touchone){
        let children = this.block_parent.children;
        //点击块反复缩小放大,播放动画
        // let click_anim = children[touchone].getComponent(cc.Animation);
        // click_anim.play("click_block");

        //同时选中改block相邻颜色的块
        let i_touch = touchone;
        let pos_touch = children[i_touch].getPosition();
        
        //符合要求的块
        let arr_touch = [];

        for(var j = 0; j < children.length; j++){
           if( j == i_touch){
             continue;
           }
           let pos_j = children[j].getPosition();
           //距离//判断是否相邻
           let Blocks_distance = (pos_touch.x - pos_j.x)*(pos_touch.x - pos_j.x) + (pos_touch.y - pos_j.y)*(pos_touch.y - pos_j.y);
           Blocks_distance = Math.sqrt(Blocks_distance);
        //    console.log("Blocks_distance:",Blocks_distance);
           if(Blocks_distance <= this.black_size + this.black_interval + 10){ 
             if(children[j].getComponent("block").blockType == children[i_touch].getComponent("block").blockType){
                let click_anim = children[j].getComponent(cc.Animation);
                let state_anim = click_anim.getAnimationState("click_block");
                if(state_anim.isPlaying){//判断是否已经加入数组
                   continue;
                }
                 //播放动画
                 click_anim.play("click_block");
                 arr_touch.push(j);
             }
           }
        }
        for(let i=0;i<arr_touch.length;i++) {
            this.touchOne(arr_touch[i]);
        }
        // console.log("arr_touch:",arr_touch.length);
    },

    //创建星星，用于消除动画
    createStar: function(pos_star,numType){
        let star = cc.instantiate(this.prefab_star);
        star.parent = this.star_parent;
        star.setPosition(pos_star);
        star.getComponent("destoryStar").init(numType);
        // this.prefab_star.getComponent("destoryStar").init(numType);
        this.random_Action(star);
        
    },

    //星星消除时的随机动画
    random_Action: function(star){
        star.scale = 0.2 +Math.random()*0.5;
        //星星移动位置
        let xx = 5 + Math.random() * 150;
        if(Math.random() > 0.5){//向右
            xx = xx * -1;
        }

        let yy = 50 + Math.random() * 50;

        let moveOut = cc.tween().by(0.1,{ position: cc.v2(xx, yy)});
        let moveIn = cc.tween().by(0.2,{ position: cc.v2(xx, -yy - (100+ Math.random() * 100 ) )},{easing: "cubicIn"});
        let moveOutIn = cc.tween().then(moveOut).then(moveIn);
        let reRotation = cc.tween().repeat(30,cc.tween().by(0.01,{angle: 90}));
        cc.tween(star)
        .parallel(
            moveOutIn,reRotation
        )
        
        //.by(0.2 + Math.random()* 0.4,xx,-yy)
        .call(()=>{
            star.destroy();
        })
        .start();
    },
    //按钮回调
    btn_callback: function (sender,str) {
        if(str == "btn_play"){
           this.layerReady.active = false;
           this.layerGame.active = true;
           this.curScore = 0;
           this.levelNum = 0;
           this.AniStart();
           //还要加一个消除所有节点的方法
        }else if(str == "btn_zhanting"){
            this.layerZhanTing.active = true;
        }else if(str == "btn_close" || str == "btn_return"){
            this.layerZhanTing.active = false;
            this.layerGame.active = true;
        }else if(str == "btn_home"){//返回首页
            this.BtnGohome();
        }else if(str == "btn_restart"){
            this.BtnRestart();
        }
        else if(str == "BtnTestTips"){
            this.IndicateFunction();
        }
        else if(str == "btnContinue"){
            this.ContinueGame();
        }else if(str.startsWith('btn_music')){
            let btn_music = this.layerZhanTing.getChildByName('btn_musicOn');
            this.is_sound = !this.is_sound;
            btn_music.getChildByName('Background').active = this.is_sound;
            btn_music.getChildByName('Off').active = !this.is_sound;
        }
        //功能按钮只有在游戏未结束时调用
        let btnToolLayout = this.layerGame.getChildByName("Btn_Tool_Layout");
        if(!this.isGameOver()){
            if(str == "btn_refresh"){
                this.StopAnim();
                this.refreshBlocks();
                this.setToolBtnInteractable(false);
    
            }else if(str == "btn_ChuiZi"){
                this.BtnChuiZi();
                if(this.node_ChuiZi.active)
                    this.setToolBtnInteractable(false);
                else 
                    this.setToolBtnInteractable(true);
                btnToolLayout.getChildByName("btn_ChuiZi").getComponent(cc.Button).interactable = true;
            }else if(str == "btn_Tuya"){
                this.BtnTuya();
                this.setToolBtnInteractable(false);
            }
        }
        
    },
    ContinueGame:function(){
       if(!this.userData.arrBblocks_save || this.userData.arrBblocks_save.length == 0){
            this.node.getChildByName("tipScript").active = true;
            cc.tween(this.node.getChildByName("tipScript"))
            .to(0.5,{opacity:255})
            .delay(0.5)
            .to(0.5,{opacity:0})
            .start();
       }else{
            this.layerReady.active = false;
            this.layerGame.active = true;

            this.levelNum =this.userData.numLevel_save;
            this.TargetScore = this.Config_guanka[this.levelNum]["targetScore"];
            this.curScore = this.userData.curScore_save;
            this.ContinueStart();
       }
    },
    BtnGohome: function(){
        this.levelNum = 0;
        this.layerGame.active = false;
        this.layerReady.active = true;
        this.layerZhanTing.active = false;
        this.clean();
    },
    BtnRestart: function(){
        this.clean();
        this.levelNum = 0;
        this.curScore = 0;
        this.AniStart();
        this.layerZhanTing.active = false;
        this.layerGame.active = true;
    },
    //设置功能按钮交互状态
    setToolBtnInteractable: function(bool){
        if(this.gameStatus != 1 ) bool =false;
        let btnToolLayout = this.layerGame.getChildByName("Btn_Tool_Layout");
        btnToolLayout.getChildByName("btn_ChuiZi").getComponent(cc.Button).interactable = bool;
        btnToolLayout.getChildByName("btn_Tuya").getComponent(cc.Button).interactable = bool;
        btnToolLayout.getChildByName("btn_shuaxing").getComponent(cc.Button).interactable = bool;
    },
    //涂鸦按钮回调
    btn_Tuya_callback: function(sender,str){
        let children = this.block_parent.children; //获取子节点
        let tuya_j = -1;
        for(let j = 0; j < children.length; j++){
            let isTuya = children[j].getComponent("block").get_IsTuya();
            if(isTuya){
                tuya_j = j;
                console.log("找到涂鸦块的位置:",tuya_j);
                break;
            }
        }
        //根据点击的按钮来涂颜色
        if(str == "btn_block_blue"){
            this.tuYaAnim(tuya_j,0);
        }else if(str == "btn_block_green"){
            this.tuYaAnim(tuya_j,1);
        }else if(str == "btn_block_purple"){
            this.tuYaAnim(tuya_j,2);
        }else if(str == "btn_block_red"){
            this.tuYaAnim(tuya_j,3);
        }else if(str == "btn_block_yellow"){
            this.tuYaAnim(tuya_j,4);
        }else if(str == "btn_cancellTuya"){
            this.bg_node_Tuya.active = false;
            this.node_Tuya.active = false;
            this.NoNTuya();
            this.setToolBtnInteractable(true);
        }
        this.time_indicate = 0;

    },
    //涂鸦后方块变色并播放动画
    tuYaAnim: function(j,color){
        let animTuya = this.node_Tuya.getComponent(cc.Animation);
        let children = this.block_parent.children;
        // animTuya.stop();
        animTuya.play("Tuya");
        let test = j;
        this.bg_node_Tuya.active = false;
        this.node_Tuya.stopAllActions();
        children[test].getComponent("block").init(color);
        this.refreshArr();
        // this.NoNTuya();
        animTuya.on('finished',()=>{
            this.node_Tuya.active = false;
            this.NoNTuya();
            this.setToolBtnInteractable(true);
        },this); 
        
    },
    //提示功能
    IndicateFunction: function(){
        let children = this.block_parent.children;
        for(let j = 0; j < children.length; j++){         
            let click_anim = children[j].getComponent(cc.Animation);
            let state_anim = click_anim.getAnimationState("click_block");
            if(state_anim.isPlaying){//判断是否已经加入数组
               return;
            }
        }
        
        for(let i = 0; i < children.length; i++){
            let j=i;
            let length = this.IsCanIndicate(j);
            if(length >= 1){
                break;
            }
        }
        return ;

    },
    //块是否可以提示
    IsCanIndicate: function(touchone){
         //同时选中改block相邻颜色的块
         let children = this.block_parent.children;
         let i_touch = touchone;
         let pos_touch = children[i_touch].getPosition();         
         //符合要求的块
         let arr_touch = [];
         for(let j = 0; j < children.length; j++){         
             if( j == i_touch){
                 continue;
            }
            let pos_j = children[j].getPosition();
            //距离//判断是否相邻
            let Blocks_distance = (pos_touch.x - pos_j.x)*(pos_touch.x - pos_j.x) + (pos_touch.y - pos_j.y)*(pos_touch.y - pos_j.y);
            Blocks_distance = Math.sqrt(Blocks_distance);
            if(Blocks_distance <= this.black_size + this.black_interval + 10){ 
              if(children[j].getComponent("block").blockType == children[i_touch].getComponent("block").blockType){
                 let click_anim = children[j].getComponent(cc.Animation);
                 let state_anim = click_anim.getAnimationState("click_block");
                 if(state_anim.isPlaying){//判断是否已经加入数组
                    continue;
                 }
                  //播放动画
                  click_anim.play("click_block");
                  arr_touch.push(j);
                }
             }
         }
        for(let i=0;i<arr_touch.length;i++) {
            this.IsCanIndicate(arr_touch[i]);
        }
        return arr_touch.length ;
    },

    clean:function(){
        let children = this.block_parent.children;
        for(let i = 0; i < children.length; i++){
            children[i].destroy();
        }
    },
    //刷新
    refreshBlocks: function(){
        let children = this.block_parent.children;
        for(let i = 0; i < children.length; i++){
            cc.tween(children[i])
            .to(0.2,{ scale: 0.2})
            // .delay(0.2)
            .call(()=>{
                let randomNum = Math.floor(Math.random() * children.length);
                let Pos_child = children[i].getPosition()
                let Pos_random = children[randomNum].getPosition()
                children[i].setPosition(Pos_random);
                children[randomNum].setPosition(Pos_child);

                cc.tween(children[i])
                .to(0.2,{ scale: 1})
                .start();
                this.setToolBtnInteractable(true);

            },this)
            .start();
        }
        this.time_indicate = 0;
        
    },
    BtnChuiZi: function(){
        this.node_ChuiZi.active = !this.node_ChuiZi.active;
        let children = this.block_parent.children;
        let randomNum = Math.floor(Math.random() * children.length);
        this.node_ChuiZi.setPosition(children[randomNum].getPosition());
        this.node_ChuiZi.x += 20;
        if(!this.node_ChuiZi.active){
            this.NoNChuiZi();
        }else{
            children[randomNum].getComponent("block").set_IsChuiZZi(this.node_ChuiZi.active);
        }

        //暂停其他动画
        this.StopAnim();
    },
    //取消所有锤子特效
    NoNChuiZi: function(){
        let children = this.block_parent.children;
        for(let i = 0; i < children.length; i++){
            children[i].getComponent("block").set_IsChuiZZi(false);
        }
    },
    //取消所有涂鸦特效
    NoNTuya: function(){
        let children = this.block_parent.children;
        for(let i = 0; i < children.length; i++){
            children[i].getComponent("block").set_IsTuya(false);
        }
    },    
    //暂停动画
    StopAnim:function(){
        let children = this.block_parent.children;

        for(let i = 0; i < children.length; i++){
            let click_anim = children[i].getComponent(cc.Animation);
            let state_anim = click_anim.getAnimationState("click_block"); 
            if(state_anim.isPlaying){
                click_anim.setCurrentTime(0,"click_block");
                click_anim.stop("click_block");
            }
        }
    },
    //涂鸦
    BtnTuya: function(){
        this.node_Tuya.active = !this.node_Tuya.active;
        let children = this.block_parent.children;
        let randomNum = -1;
        this.node_Tuya.stopAllActions();
        if(children.length > 0){
            randomNum = Math.floor(Math.random() * children.length);
            this.node_Tuya.setPosition(children[randomNum].getPosition());
            this.node_Tuya.x = children[randomNum].x+ 20;
            this.node_Tuya.y = children[randomNum].y+ 40;
            if(!this.node_Tuya.active){
                this.NoNTuya();
            }else{
                children[randomNum].getComponent("block").set_IsTuya(this.node_Tuya.active);
            }

        }
        let moveUp = cc.moveBy(0.2,0,20);
        let moveDown = cc.moveBy(0.2,0,-20);
        let seq = cc.repeatForever(cc.sequence(moveUp,moveDown))
        this.node_Tuya.runAction(seq);

        this.btnBg_Tuya_apprence(randomNum);
        this.bg_node_Tuya.active = this.node_Tuya.active;
        this.StopAnim();
    },
    //涂鸦背景按钮的显现
    btnBg_Tuya_apprence: function(block_i){
        let children = this.block_parent.children;
        let block_type = children[block_i].getComponent("block").blockType;
        this.bg_node_Tuya.getChildByName("btn_block_blue").active = true;
        this.bg_node_Tuya.getChildByName("btn_block_green").active = true;
        this.bg_node_Tuya.getChildByName("btn_block_purple").active = true;
        this.bg_node_Tuya.getChildByName("btn_block_red").active = true;
        this.bg_node_Tuya.getChildByName("btn_block_yellow").active = true;
        if(block_type == 0){
            this.bg_node_Tuya.getChildByName("btn_block_blue").active = false;
        }else if(block_type == 1){
            this.bg_node_Tuya.getChildByName("btn_block_green").active = false;
        }else if(block_type == 2){
            this.bg_node_Tuya.getChildByName("btn_block_purple").active = false;
        }else if(block_type == 3){
            this.bg_node_Tuya.getChildByName("btn_block_red").active = false;
        }else if(block_type == 4){
            this.bg_node_Tuya.getChildByName("btn_block_yellow").active = false;
        }
    },
    //复活
    BtnFH: function(){
        this.curScore = this.userData.numScore_fh;
        this.levelNum -= 1;
        this.clean();
        this.AniStart();
        this.layerZhanTing.active = false;
        this.layerGame.active = true;
    },

    update (dt) {//1秒执行60次
        this.time_indicate++;
        if(this.time_indicate >= 5 * 60 && this.gameStatus == 1){
            this.time_indicate = 0;
            if(this.node_ChuiZi.active || this.node_Tuya.active){//有锤子或者涂鸦特效就不提示
                return;
            }
            this.IndicateFunction();//5秒执行一次
        }

    },
});
